package org.dlx.drpc.core.client;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class MessagePromisor extends ChannelHandlerAdapter
{
    private static Logger logger = LoggerFactory.getLogger(MessagePromisor.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        logger.trace("receive response");
        Promise pro = ctx.channel().attr(AttributeMapKeys.RPC_PROMISE).getAndRemove();
        pro.setResult(msg);
        pro.getPromise().setSuccess();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        logger.debug("",cause);
        Promise pro = ctx.channel().attr(AttributeMapKeys.RPC_PROMISE).getAndRemove();
        if(pro != null)
            pro.getPromise().setFailure(cause);
        ctx.close();
    }
}
